--[[
-- Author:      feilong
-- DateTime:    2018-04-23 17:19:33
-- Description: lua打印日志服务用于替换 skynet 自带的logger服务

--]]

local skynet = require("skynet.manager")

local Service = class("Logger")

function Service:ctor()
    self.handler = new("logger.handler")
    self:register()
end

function Service:register()
    g.dispatch:register('start', handler(self, self.onStart))
    g.dispatch:register('close', handler(self, self.onClose))
end

function Service:onStart()


    print("logger_service onStart")

    return "ok"
end

function Service:onClose()
end


local service
--服务启动后调用
skynet.init(function ( ... )

end)

local function func(_, address, msg)
    -- reopen signal
    local str = string.format("[SYSTEM:%08x] %s", address, msg)
    print("SYSTEMlog:", str)
    if service then
        service.handler:saveData(str)
    end
end

skynet.register_protocol({
    name = "SYSTEM",
    id = skynet.PTYPE_SYSTEM,
    unpack = function(...) return ... end,
    dispatch = func
})

skynet.register_protocol( {
    name = "text",
    id = skynet.PTYPE_TEXT,
    unpack = skynet.tostring,
    dispatch = function(_, address, msg)
        --收到消息
        local str = string.format("[:%08x] %s", address, msg)
        print("textlog:",str)
        if service then
            service.handler:saveData(str)
        end
    end
})

--启动服务
skynet.start(function()
    local service_name = ".logger"
    g.init(service_name)
    service = Service:new()
    service:onStart()
    g.service = service
end)

